package com.boarsoft.message.sofamq;

import java.io.Closeable;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.openmessaging.api.Message;
import io.openmessaging.api.OMS;
import io.openmessaging.api.Producer;
import io.openmessaging.api.SendResult;

public class SofaMQProducer implements Closeable {
	private static final Logger log = LoggerFactory.getLogger(SofaMQProducer.class);
	protected SofaMqConfig sofaMqConfig;
	protected Producer producer;

	@Override
	public void close() throws IOException {
		producer.shutdown();
		producer = null;
	}

	public void init() {
		this.producer = OMS.builder().driver("sofamq")//
				.build(this.sofaMqConfig.getBaseMqProperties())//
				.createProducer(this.sofaMqConfig.getProdMqProperties());
		this.producer.start();
	}

	public void sendMessage(Message msg) {
		SendResult result = null;
		try {
			result = this.producer.send(msg);
			// TODO
			log.debug("Sent sofamq message {}", result.getMessageId());
		} catch (Throwable e) {
			throw e;
		}
	}

	public SofaMqConfig getSofaMqConfig() {
		return sofaMqConfig;
	}

	public void setSofaMqConfig(SofaMqConfig sofaMqConfig) {
		this.sofaMqConfig = sofaMqConfig;
	}

	public Producer getProducer() {
		return producer;
	}

	public void setProducer(Producer producer) {
		this.producer = producer;
	}
}
